import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class DeleteGoodsServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");

        String goods_id = request.getParameter("goods_id");

        String url = "jdbc:mysql://localhost:3306/shop?useSSL=false&serverTimezone=UTC&user=root&password=123456";
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            try (Connection connection = DriverManager.getConnection(url)) {
                String sql = "DELETE FROM goods WHERE goods_id=?";
                try (PreparedStatement statement = connection.prepareStatement(sql)) {
                    statement.setString(1, goods_id);
                    int rowsAffected = statement.executeUpdate();
                    if (rowsAffected > 0) {
                        response.getWriter().println("<script>alert('商品删除成功！');window.location.href='menu/device/3-1.jsp';</script>");
                    } else {
                        response.getWriter().println("<script>alert('商品删除失败！');window.location.href='menu/device/3-1.jsp';</script>");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println("<script>alert('商品删除过程中发生错误！');window.location.href='menu/device/3-1.jsp';</script>");
        }
    }
}